package control.board;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.board.BoardService;
import model.board.BoardVO;
import model.board.ReflyVO;
import model.boardlist.BoardListService;
import model.boardlist.BoardListVO;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class BoardController extends MultiActionController{
	private BoardService boardService;
	private String path;
	private BoardListService boardListService;
	public BoardController(BoardService boardService, String path){
		this.boardService=boardService;
		this.path=path;
	}
	public void setBoardListService(BoardListService boardListService) {
		this.boardListService = boardListService;
	}
	
	/**
	 * 글쓰기 폼
	 */
	public ModelAndView writeView(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		List<BoardListVO> list = boardListService.boardList();
		return new ModelAndView("write","list", list);
	}	
	/**
	 * 방명록 list 받아오는 곳.
	 */
	public ModelAndView guestWrite(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception{
		HashMap map=new HashMap();
		map.put("boardNo", request.getParameter("board_no"));
		System.out.println("다녀오기!!");
		return new ModelAndView("guestList","lvo",boardService.getContentList(map));
	}
	
	/**
	 * 글쓰기
	 */
	int content_no=0;
	public ModelAndView write(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, BoardVO bvo) throws Exception{
		if(request.getParameter("kind").equals("guest")){
			boardService.write(bvo);
			System.out.println("flag true로 글써짐.");
		request.setAttribute("kind", request.getParameter("kind"));
		return new ModelAndView("flag","board_no", request.getParameter("board_no"));
		}
		Boolean flag=(Boolean) session.getAttribute("flag");
		if(flag!=null){
			boardService.write(bvo);
			if(request.getParameter("kind").equals("file") ||
					request.getParameter("kind").equals("picture")){ //파일게시판이나 사진 게시판에서만 업로드
				//----------------------------------파일 업로드 시작-----------------------------
				MultipartFile mfile=bvo.getUploadFile();
				//파일 사이즈가 0 인 경우도 등록시켜려면 조건 추가 
				if(mfile.isEmpty()==false||mfile.getOriginalFilename()!=""){
					String fileName=mfile.getOriginalFilename();				
					bvo.setOrgfilename(fileName);
					// 시간_파일명으로 저장 
					String newfilename=System.currentTimeMillis()+"_"+fileName;
					bvo.setNewfilename(newfilename);
					File copyFile=new File(path+newfilename);
					// 업로드..
					mfile.transferTo(copyFile);
					boardService.uploadFileBoard(bvo); // 업로드후 DB에 파일명 등록
				}
				//----------------------------------파일 업로드 끝--------------------------------
			}	
			session.removeAttribute("flag");
			content_no=bvo.getContent_no();
		}else{//f5키 눌렀을때
			return new ModelAndView("showContent","svo",boardService.showContent(content_no+""));
		}
		return new ModelAndView("showContent","svo",boardService.showContent(bvo.getContent_no()+""));
	}
	
	/**
	 * 글목록 보기
	 */
	public ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception{	
		String boardKind=request.getParameter("kind");
		String boardNo=request.getParameter("board_no");
		String pageNo=request.getParameter("pageNo");
		String view=request.getParameter("view"); // 목록 x개씩 보기
		String path="";
		if(boardKind.equals("guest")){
			path="guestList";
		}else if(boardKind.equals("picture")){
			path="pictureList";
		}else{
			path="boardList";
		}
		HashMap map=new HashMap();
		map.put("boardNo", boardNo);
		map.put("pageNo", pageNo);
		map.put("view", view);
		return new ModelAndView(path,"lvo",boardService.getContentList(map));
	}

	/**
	 * 게시글 보기
	 */
	public ModelAndView showContent(HttpServletRequest request,
			HttpServletResponse response) throws Exception{	
		return new ModelAndView("showContent","svo",boardService.showContent(request.getParameter("no")));
	}
	
	/**
	 * 파일 다운로드
	 */
	public ModelAndView download(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String orgfilename=request.getParameter("orgfilename");
		String newfilename=request.getParameter("newfilename");
		HashMap map=new HashMap();
		// 파일 저장소에 파일을 읽어 다운로드 시켜야 하므로 파일명에 path를 더한다. 
		map.put("newfilename",path+File.separator+ request.getParameter("newfilename"));
		//다운로드 시킬 원본 파일명 
		map.put("orgfilename", orgfilename);
		System.out.println("이거다"+map);
		return new ModelAndView("downloadView",map);
	}
	
	/**
	 * 게시글 삭제
	 */
	public ModelAndView deleteBoard(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception{
		String no=request.getParameter("no");
		Boolean flag=(Boolean) session.getAttribute("showContentFlag");
		String viewPath="";
		String boardKind=request.getParameter("kind");
		if(boardKind.equals("guest")){
			boardService.deleteBoard(no);
			request.setAttribute("kind", request.getParameter("kind"));
			return new ModelAndView("flag","board_no", request.getParameter("board_no"));
		}else if(boardKind.equals("picture")){
			viewPath="pictureList";
		}else{
			viewPath="boardList";
		}
		if(flag!=null){
			BoardVO bvo=boardService.showContent(no).getBvo();
			boardService.deleteBoard(no);
			if(request.getParameter("kind").equals("file") ||
				request.getParameter("kind").equals("picture")){ //파일게시판이나 사진 게시판에서만 파일삭제
				String newfilename=bvo.getNewfilename();
				//file이 존재하면 디렉토리의 업로드된 파일을 삭제한다. 
				if(newfilename!=null&&!newfilename.equals("")){
					boardService.deleteFile(path+newfilename);
				}
			}
			session.removeAttribute("showContentFlag");
		}
		HashMap map=new HashMap();
		map.put("boardNo", request.getParameter("board_no"));
		return new ModelAndView(viewPath,"lvo",boardService.getContentList(map));
	}
	
	/**
	 * 게시글 수정 폼
	 */
	public ModelAndView updateView(HttpServletRequest request,
			HttpServletResponse response ) throws Exception{
		return new ModelAndView("updateBoard","bvo",boardService.showContent(request.getParameter("no")).getBvo());
	}
	
	/**
	 * 게시글 수정
	 */
	public ModelAndView updateBoard(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, BoardVO bvo) throws Exception{
		String no=request.getParameter("no");
		Boolean flag=(Boolean) session.getAttribute("flag");
		if(flag!=null){
			bvo.setContent_no(Integer.parseInt(no));
			boardService.updateBoard(bvo);
			if(request.getParameter("kind").equals("file") ||
					request.getParameter("kind").equals("picture")){ //파일게시판이나 사진 게시판에서만 업로드
				//----------------------------------파일 업로드 시작-----------------------------
				if(bvo.getUploadFile()!=null){
					MultipartFile mfile=bvo.getUploadFile();
					//파일 사이즈가 0 인 경우도 등록시켜려면 조건 추가 
					if(mfile.isEmpty()==false||!mfile.getOriginalFilename().equals("")){
						String fileName=mfile.getOriginalFilename();				
						bvo.setOrgfilename(fileName);
						// 시간_파일명으로 저장 
						String newfilename=System.currentTimeMillis()+"_"+fileName;
						bvo.setNewfilename(newfilename);
						File copyFile=new File(path+newfilename);
						// 업로드..
						mfile.transferTo(copyFile);
						boardService.uploadFileBoard(bvo); // 업로드후 DB에 파일명 등록
					}
				}
				//----------------------------------파일 업로드 끝--------------------------------
			}
			session.removeAttribute("flag");
		}
		return new ModelAndView("showContent","svo",boardService.showContent(no));
	}

	/**
	 * 방명록 => 수정버튼 사용시
	 */
	public ModelAndView modifylist(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		HashMap map=new HashMap();
		map.put("boardNo", request.getParameter("board_no"));
		map.put("pageNo", request.getParameter("pageNo"));
		return new ModelAndView("JsonView","lvo",boardService.getContentList(map));
	}
	/**
	 * 방명록 글 수정
	 * @param request
	 * @param response
	 * @param bvo
	 * @return
	 * @throws Exception
	 */
	public ModelAndView guestUpdateBoard(HttpServletRequest request,
			HttpServletResponse response,BoardVO bvo) throws Exception{
		String no=request.getParameter("no");
		bvo.setContent_no(Integer.parseInt(no));
		System.out.println(bvo.toString());
		boardService.updateBoard(bvo);
		HashMap map=new HashMap();
		map.put("boardNo", request.getParameter("board_no"));
		map.put("pageNo", request.getParameter("pageNo"));
		return new ModelAndView("guestList","lvo",boardService.getContentList(map));
	}

	/**
	 * 파일 삭제
	 */
	public ModelAndView deleteFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String no=request.getParameter("no");
		String newfilename=request.getParameter("newfilename");
		//file이 존재하면 디렉토리의 업로드된 파일을 삭제한다. 
		if(newfilename!=null||!newfilename.equals("")){
			boardService.deleteFile(path+File.separator+ request.getParameter("newfilename"));
		}
		boardService.deleteFileBoard(no);
		return new ModelAndView("updateBoard","bvo",boardService.showContent(no).getBvo());
	}
	
	/**
	 * 리플 폼
	 */
	public ModelAndView answerView(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		return new ModelAndView("answer","bvo",boardService.showContent(request.getParameter("no")).getBvo());
	}
	
	/**
	 * 리플 쓰기
	 */
	public ModelAndView answerBoard(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, BoardVO bvo) throws Exception{
		Boolean flag=(Boolean) session.getAttribute("flag");
		if(flag!=null){
			boardService.answerBoard(bvo);
			if(request.getParameter("kind").equals("file") ||
					request.getParameter("kind").equals("picture")){ //파일게시판이나 사진 게시판에서만 업로드
				//----------------------------------파일 업로드 시작-----------------------------
				MultipartFile mfile=bvo.getUploadFile();
				//파일 사이즈가 0 인 경우도 등록시켜려면 조건 추가 
				if(mfile.isEmpty()==false||mfile.getOriginalFilename()!=""){
					String fileName=mfile.getOriginalFilename();				
					bvo.setOrgfilename(fileName);
					// 시간_파일명으로 저장 
					String newfilename=System.currentTimeMillis()+"_"+fileName;
					bvo.setNewfilename(newfilename);
					File copyFile=new File(path+newfilename);
					// 업로드..
					mfile.transferTo(copyFile);
					boardService.uploadFileBoard(bvo); // 업로드후 DB에 파일명 등록
				}
				//----------------------------------파일 업로드 끝--------------------------------
			}
			content_no=bvo.getContent_no();//f5눌렀을때 찾아갈 게시글 전역변수
			session.removeAttribute("flag");
		}else{//f5키 눌렀을때
			return new ModelAndView("showContent","svo",boardService.showContent(content_no+""));
		}
		return new ModelAndView("showContent","svo",boardService.showContent(bvo.getContent_no()+""));
	}		
	
	/**
	 * 미니 리플 쓰기
	 */
	public ModelAndView writeMiniRefly(HttpServletRequest request,
			HttpServletResponse response, HttpSession session, ReflyVO rvo) throws Exception{
		boardService.writeRefly(rvo);
		String content_no=rvo.getContent_no()+"";
		HashMap map=new HashMap();
		map.put("no", content_no);
		map.put("kind", request.getParameter("kind"));
		map.put("view", request.getParameter("view"));
		return new ModelAndView("/board_view/intoShowContent","map",map);
	}	

	/**
	 * 미니 리플 수정
	 */
	public ModelAndView modifyMiniRefly(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String content_no=request.getParameter("content_no");
		String no=request.getParameter("no");
		String content=request.getParameter("content");
		HashMap map=new HashMap();
		map.put("no", no);
		map.put("content", content);
		boardService.modifyRefly(map);
		return new ModelAndView("showContent","svo",boardService.showContent(content_no));
	}	
	
	/**
	 * 미니 리플 삭제
	 */
	public ModelAndView deleteMiniRefly(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String no=request.getParameter("no");
		String content_no=request.getParameter("content_no");
		boardService.deleteRefly(no);
		HashMap map=new HashMap();
		map.put("no", content_no);
		map.put("kind", request.getParameter("kind"));
		map.put("view", request.getParameter("view"));
		return new ModelAndView("/board_view/intoShowContent","map",map);
	}
	
	/**
	 * 덧글 쓰기 삭제할 때 f5막기위해 거치는 곳
	 */
	public ModelAndView intoShowContent(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String content_no=request.getParameter("no");
		return new ModelAndView("showContent","svo",boardService.showContent(content_no));
	}
	
	/**
	 * 게시글 검색
	 */
	public ModelAndView searchBoard(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String board_no=request.getParameter("board_no");
		String str=request.getParameter("str");
		String kind=request.getParameter("searchKind");
		String view=request.getParameter("view");
		String page_no=request.getParameter("pageNo");
		HashMap map=new HashMap();
		map.put("board_no", board_no);
		map.put("kind", kind);
		map.put("str", str);
		map.put("view", view);
		map.put("page_no", page_no);
							System.out.println("controller : "+map);
		return new ModelAndView("boardList","lvo",boardService.searchBoard(map));
	}
}






















